package com.gzu.finalwork.courier.service;

import com.gzu.finalwork.courier.mapper.CourierMapper;
import com.gzu.finalwork.entity.user.DeliveryOrders;
import com.gzu.finalwork.entity.courier.DeliveryAssignments;
import com.gzu.finalwork.entity.user.DeliveryTrack;
import com.gzu.finalwork.entity.courier.Couriers;
import com.gzu.finalwork.common.utils.AjaxResult;
import com.gzu.finalwork.user.service.DeliveryTrackService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CourierService {

    @Autowired
    private CourierMapper courierMapper;
    
    @Autowired
    private DeliveryTrackService deliveryTrackService;

    /**
     * 获取可接订单列表（状态为0-待揽收）
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @return 可接订单列表
     */
    public Object getAvailableOrders(int pageNum, int pageSize) {
        try {
            // 计算偏移量（MyBatis分页从0开始）
            int offset = (pageNum - 1) * pageSize;
            
            List<DeliveryOrders> orders = courierMapper.selectAvailableOrders(offset, pageSize);
            int total = courierMapper.countAvailableOrders();
            
            Map<String, Object> resultData = new HashMap<>();
            resultData.put("list", orders);
            resultData.put("total", total);
            resultData.put("pageNum", pageNum);
            resultData.put("pageSize", pageSize);
            
            return AjaxResult.success("获取可接订单成功", resultData);
        } catch (Exception e) {
            return AjaxResult.error(500, "获取可接订单失败：" + e.getMessage());
        }
    }

    /**
     * 配送员接单
     * @param orderId 订单ID
     * @param courierId 配送员ID
     * @param remark 备注
     * @return 接单结果
     */
    @Transactional
    public Object acceptOrder(Long orderId, Long courierId, String remark) {
        try {
            // 1. 检查订单是否存在且状态为待揽收
            DeliveryOrders order = courierMapper.selectOrderById(orderId);
            if (order == null) {
                return AjaxResult.error(404, "订单不存在");
            }
            
            if (order.getOrderStatus() != 0) {
                return AjaxResult.error(400, "订单状态不正确，无法接单");
            }
            
            // 2. 更新订单状态为待发货(1)并分配配送员
            int updateResult = courierMapper.updateOrderStatus(orderId, courierId, 1);
            if (updateResult <= 0) {
                return AjaxResult.error(500, "更新订单状态失败");
            }
            
            // 3. 创建配送记录
            DeliveryAssignments assignment = new DeliveryAssignments();
            assignment.setOrderId(orderId);
            assignment.setCourierId(courierId);
            assignment.setStatus(0); // 配送状态：0-已接单
            assignment.setAssignedAt(LocalDateTime.now());
            assignment.setRemark(remark);
            
            int insertResult = courierMapper.insertDeliveryAssignment(assignment);
            if (insertResult <= 0) {
                throw new RuntimeException("创建配送记录失败");
            }
            
            // 4. 创建物流轨迹记录
            createAcceptOrderTrack(orderId, courierId, order.getSenderAddress());
            
            Map<String, Object> resultData = new HashMap<>();
            resultData.put("orderId", orderId);
            resultData.put("orderNumber", order.getOrderNumber());
            resultData.put("assignmentId", assignment.getAssignmentId());
            resultData.put("assignedAt", assignment.getAssignedAt());
            
            return AjaxResult.success("接单成功", resultData);
            
        } catch (Exception e) {
            return AjaxResult.error(500, "接单失败：" + e.getMessage());
        }
    }

    /**
     * 获取配送员的配送记录
     * @param courierId 配送员ID
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @return 配送记录列表
     */
    public Object getCourierAssignments(Long courierId, int pageNum, int pageSize) {
        try {
            // 计算偏移量
            int offset = (pageNum - 1) * pageSize;
            
            List<DeliveryAssignments> assignments = courierMapper.selectAssignmentsByCourier(courierId, offset, pageSize);
            int total = courierMapper.countAssignmentsByCourier(courierId);
            
            Map<String, Object> resultData = new HashMap<>();
            resultData.put("list", assignments);
            resultData.put("total", total);
            resultData.put("pageNum", pageNum);
            resultData.put("pageSize", pageSize);
            
            return AjaxResult.success("获取配送记录成功", resultData);
        } catch (Exception e) {
            return AjaxResult.error(500, "获取配送记录失败：" + e.getMessage());
        }
    }

    /**
     * 根据订单ID获取订单详情
     * @param orderId 订单ID
     * @return 订单详情
     */
    public Object getOrderDetails(Long orderId) {
        try {
            DeliveryOrders order = courierMapper.selectOrderById(orderId);
            if (order == null) {
                return AjaxResult.error(404, "订单不存在");
            }
            
            return AjaxResult.success("获取订单详情成功", order);
        } catch (Exception e) {
            return AjaxResult.error(500, "获取订单详情失败：" + e.getMessage());
        }
    }

    /**
     * 根据用户ID获取配送员ID
     * @param userId 用户ID
     * @return 配送员ID
     */
    public Long getCourierIdByUserId(Long userId) {
        return courierMapper.selectCourierIdByUserId(userId);
    }

    /**
     * 根据订单ID获取物流轨迹
     * @param orderId 订单ID
     * @param session HTTP会话
     * @return 物流轨迹信息
     */
    public Object getDeliveryTrack(Long orderId, HttpSession session) {
        try {
            // 从session获取当前登录用户ID
            Long userId = (Long) session.getAttribute("userId");
            if (userId == null) {
                return AjaxResult.error(401, "用户未登录");
            }
            
            // 获取物流轨迹
            DeliveryTrack track = deliveryTrackService.getTrackByOrderId(orderId);
            if (track == null) {
                return AjaxResult.error(404, "暂无物流轨迹信息");
            }
            
            return AjaxResult.success("获取物流轨迹成功", track);
        } catch (Exception e) {
            return AjaxResult.error(500, "获取物流轨迹失败：" + e.getMessage());
        }
    }

    /**
     * 添加物流轨迹
     * @param orderId 订单ID
     * @param location 位置信息
     * @param remark 备注
     * @param session HTTP会话
     * @return 添加结果
     */
    public Object addDeliveryTrack(Long orderId, String location, String remark, HttpSession session) {
        try {
            // 从session获取当前登录用户ID
            Long userId = (Long) session.getAttribute("userId");
            if (userId == null) {
                return AjaxResult.error(401, "用户未登录");
            }
            
            // 根据userId查询对应的配送员ID
            Long courierId = courierMapper.selectCourierIdByUserId(userId);
            if (courierId == null) {
                return AjaxResult.error(403, "当前用户不是配送员");
            }
            
            // 创建轨迹记录
            DeliveryTrack.TrackRecord trackRecord = new DeliveryTrack.TrackRecord();
            trackRecord.setTimestamp(LocalDateTime.now());
            trackRecord.setStatus(4); // 默认配送中状态
            trackRecord.setDescription("配送中");
            
            // 设置位置信息
            DeliveryTrack.Location locationObj = new DeliveryTrack.Location();
            locationObj.setAddress(location);
            trackRecord.setLocation(locationObj);
            
            // 设置操作员信息
            trackRecord.setOperator("配送员" + courierId);
            
            // 设置备注
            if (remark != null && !remark.trim().isEmpty()) {
                trackRecord.setRemark(remark);
            }
            
            // 调用DeliveryTrackService添加轨迹记录
            return deliveryTrackService.addTrackRecord(orderId, trackRecord);
            
        } catch (Exception e) {
            return AjaxResult.error(500, "添加物流轨迹失败：" + e.getMessage());
        }
    }

    /**
     * 创建接单轨迹记录
     * @param orderId 订单ID
     * @param courierId 配送员ID
     * @param senderAddress 寄件地址
     */
    private void createAcceptOrderTrack(Long orderId, Long courierId, String senderAddress) {
        try {
            // 检查是否已经存在轨迹记录，如果不存在则创建
            DeliveryTrack existingTrack = deliveryTrackService.getTrackByOrderId(orderId);
            if (existingTrack == null) {
                // 获取订单信息创建轨迹
                DeliveryOrders order = courierMapper.selectOrderById(orderId);
                if (order != null) {
                    deliveryTrackService.createTrack(orderId, order.getOrderNumber());
                }
            }
            
            // 创建接单轨迹记录
            DeliveryTrack.TrackRecord trackRecord = new DeliveryTrack.TrackRecord();
            trackRecord.setTimestamp(LocalDateTime.now());
            trackRecord.setStatus(3); // 已揽件状态
            trackRecord.setDescription("配送员已接单，准备揽件");
            
            // 设置位置信息（使用寄件地址）
            DeliveryTrack.Location locationObj = new DeliveryTrack.Location();
            locationObj.setAddress(senderAddress != null ? senderAddress : "配送起点");
            trackRecord.setLocation(locationObj);
            
            // 设置操作员信息
            trackRecord.setOperator("配送员" + courierId);
            trackRecord.setRemark("配送员已接单，正在前往揽件");
            
            // 添加轨迹记录
            deliveryTrackService.addTrackRecord(orderId, trackRecord);
            
        } catch (Exception e) {
            // 记录日志但不影响接单流程
            System.err.println("创建接单轨迹记录失败: " + e.getMessage());
        }
    }

    /**
     * 获取配送员仪表盘数据
     * @param courierId 配送员ID
     * @return 仪表盘统计数据
     */
    public Object getDashboardData(Long courierId) {
        try {
            Map<String, Object> dashboardData = new HashMap<>();
            
            // 1. 今日配送 - 已完成配送的订单数（今天）
            int todayCompleted = courierMapper.countTodayCompletedOrders(courierId);
            
            // 2. 进行中 - 正在配送的订单数（状态为1,2的订单）
            int inProgress = courierMapper.countInProgressOrders(courierId);
            
            // 3. 可接订单 - 待接单的订单数（状态为0）
            int availableOrders = courierMapper.countAvailableOrders();
            
            // 4. 今日送达 - 今天成功送达的订单数（状态为4且今天完成）
            int todayDelivered = courierMapper.countTodayDeliveredOrders(courierId);
            
            // 5. 当前配送任务列表（最近5个任务）
            List<DeliveryAssignments> currentTasks = courierMapper.selectCurrentTasks(courierId, 5);
            
            // 组装数据
            dashboardData.put("todayCompleted", todayCompleted);
            dashboardData.put("inProgress", inProgress);
            dashboardData.put("availableOrders", availableOrders);
            dashboardData.put("todayDelivered", todayDelivered);
            dashboardData.put("currentTasks", currentTasks);
            
            // 添加汇总信息
            Map<String, Object> summary = new HashMap<>();
            summary.put("totalToday", todayCompleted + todayDelivered);
            summary.put("workload", inProgress + availableOrders);
            dashboardData.put("summary", summary);
            
            return AjaxResult.success("获取仪表盘数据成功", dashboardData);
            
        } catch (Exception e) {
            return AjaxResult.error(500, "获取仪表盘数据失败：" + e.getMessage());
        }
    }

} 